﻿using LanDBom.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;

namespace LanDBom
{
    public class MyAuthentication
    {
        public static HttpCookie AuthCookie()
        {
            return HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
        }
        public static void SerCankie(string UserName, string UserID, string Rights)
        {
            String UserData = UserID + "#" + Rights;
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, UserName, DateTime.Now, DateTime.Now.AddMinutes(60), false, UserData);
            string cnyTickiet = FormsAuthentication.Encrypt(ticket); // 加密
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cnyTickiet);
            HttpContext.Current.Response.Cookies.Add(cookie);
        }
        public static bool IsLogin()
        {
            return AuthCookie() != null;
        }
        //注销--脱出登录功能
        public static void LoginOut()
        {
            FormsAuthentication.SignOut();
        }
        public static string GetUserName()
        {
            if (IsLogin())
            {
                FormsAuthenticationTicket authenticationTicket = FormsAuthentication.Decrypt(AuthCookie().Value);
                return authenticationTicket.Name;
            }
            else return "";
        }
        public static int GetUserId()
        {
            if (IsLogin())
            {
                //解密
                FormsAuthenticationTicket authen = FormsAuthentication.Decrypt(AuthCookie().Value);
                string[] UserData = authen.UserData.Split('#');
                if (UserData.Length > 0) return int.Parse(UserData[0]);
                else return 0;
            }
            else return 0;
        }
        public static string GetRighhts()
        {
            if (IsLogin())
            {
                FormsAuthenticationTicket authenticationTicket = FormsAuthentication.Decrypt(AuthCookie().Value);
                string[] UserData = authenticationTicket.UserData.Split('#');
                if (UserData.Length > 1)
                {
                    return UserData[1].ToString();
                }
                else { return ""; }
            }
            else return "";
        }
        public static Dengli GetUsers()
        {
            int uid = GetUserId();
            LDbaseEntities db = new LDbaseEntities();
            Dengli da = db.Dengli.Include("F_BuMen").Include("F_Shen").Where(s=>s.DE_ID==uid).FirstOrDefault();
            return da;
        }
    }
}